package io.zbc.leetcode.solutions;

import java.util.Arrays;
import java.util.HashMap;

/**
 * <a href="https://leetcode.cn/problems/two-sum/">1. 两数之和</a>
 *
 * @author zbc
 * @date 2023/1/9
 */
public class Solution_1 {
    public static void main(String[] args) {
        Solution_1 solution_1 = new Solution_1();
        System.out.println(Arrays.toString(solution_1.twoSumHash(new int[]{2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(solution_1.twoSumHash(new int[]{3, 2, 4}, 6)));
        System.out.println(Arrays.toString(solution_1.twoSumHash(new int[]{3, 3}, 6)));
    }

    /**
     * 方法一：暴力枚举
     */
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
        return result;
    }

    /**
     * 方法二：哈希表
     */
    public int[] twoSumHash(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}